import { useKeyPress } from 'ahooks'
import { useDispatch, useSelector } from 'react-redux'
import { deleteComponent, changeSelected, copyComponent, pasteComponent } from '@/store/componentsReducer'
import { StateType } from '@/store'

// 判断当前焦点是否在可操作的元素上
const isActionElementValid = () => {
  const actionElement = document.activeElement
  return actionElement === document.body ? true : false
}

const useBindCanvasKeyPress = () => {
  const dispatch = useDispatch()
  const { selectedId, componentList } = useSelector((state: StateType) => state.components)
  // 删除组件
  useKeyPress(['delete', 'backspace'], () => {
    if (!isActionElementValid()) return
    dispatch(deleteComponent())
  })

  // 复制组件
  useKeyPress(['ctrl.c', 'meta.c'], () => {
    if (!isActionElementValid()) return
    dispatch(copyComponent())
  })

  // 粘贴组件
  useKeyPress(['ctrl.v', 'meta.v'], () => {
    if (!isActionElementValid()) return
    dispatch(pasteComponent())
  })

  // 选中上一个
  useKeyPress(['uparrow'], () => {
    if (!isActionElementValid()) return
    const index = componentList.findIndex(item => item.fe_id === selectedId)
    if (index === 0 || index === -1) return
    const prev = componentList[index - 1]
    dispatch(changeSelected(prev.fe_id || ''))
  })

  // 选中下一个
  useKeyPress(['downarrow'], () => {
    if (!isActionElementValid()) return
    const index = componentList.findIndex(item => item.fe_id === selectedId)
    if (index === componentList.length - 1 || index === -1) return
    const next = componentList[index + 1]
    dispatch(changeSelected(next.fe_id || ''))
  })
}

export default useBindCanvasKeyPress
